﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AtletIS.Shared.AtletisService;
using AtletIS.Shared.Data.aDbDataSetTableAdapters;
using AtletIS.Shared.Data;
using AtletIS.Shared.Helpers;
using System.ServiceModel;

namespace AtletIS.Shared.Forms
{
    public partial class frmSyncWeb : Form
    {
        private SyncParameters syncParams;
        private BackgroundWorker bw;
        private DateTime dtStart;

        private bool bResult = false;
        private bool bCompetition = false;
        private bool bTables = false;

        private int error = 0;
        private string error_text = string.Empty;

        #region Form

        // Constructor
        public frmSyncWeb()
        {
            InitializeComponent();
            this.Icon = Properties.Resources.AtletIS64;

            this.bw = new BackgroundWorker();
            this.bw.WorkerReportsProgress = true;
            this.bw.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
            this.bw.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker_ProgressChanged);
            this.bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted);
        }

        // Form load
        private void frmSyncWeb_Load(object sender, EventArgs e)
        {
            this.dtpDateFrom.Value = DateTime.Now.AddDays(-10);
            this.dtpDateTo.Value = DateTime.Now.AddDays(10);
        }

        // Close
        private void tsbClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #endregion

        #region Get competitions

        private void btnGetCompetitions_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;

                this.syncParams = new SyncParameters();
                syncParams.DateFrom = this.dtpDateFrom.Value;
                syncParams.DateFromSpecified = true;
                syncParams.DateTo = this.dtpDateTo.Value;
                syncParams.DateToSpecified = true;
                syncParams.ActiveTable = AtletisService.Tables.Competitions;
                syncParams.ActiveTableSpecified = true;

                DataTable dt;
                using (AtletisServiceClient client = new AtletisServiceClient())
                {
                    dt = client.GetTable(syncParams, ref this.error, ref this.error_text);
                }

                if (dt != null && dt.Rows.Count > 0)
                {
                    this.dgvData.DataSource = dt;
                    this.FormatDGV();
                }
                else
                {
                    this.dgvData.DataSource = null;
                }
            }
            catch (Exception ex)
            {
                this.ShowError(ex);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void FormatDGV()
        {
            if (this.dgvData != null)
            {
                if (this.dgvData.Columns != null && this.dgvData.Columns.Count > 0)
                {
                    foreach (DataGridViewColumn col in this.dgvData.Columns)
                    {
                        col.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                    }
                }
            }
        }

        private void ShowError(Exception ex)
        {
            if (this.error > 0)
            {
                MessageBox.Show("Chyba z WS: " + this.error_text, "AtletisService", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                this.error = 0;
                this.error_text = string.Empty;
            }
            else
            {
                MessageBox.Show("Chyba z APP: " + ex.Message, "AtletisService", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region Buttons

        private void tsbTables_Click(object sender, EventArgs e)
        {
            if (this.bw.IsBusy)
            {
                MessageBox.Show("Prebieha download, čakajte prosím!", "Download", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                int tables = 0;
                if (chkCategories.Checked) tables += 1;
                if (chkDisciplines.Checked) tables += 2;
                if (chkCountries.Checked) tables += 1;
                if (chkClubs.Checked) tables += 2;
                if (chkCompetitors.Checked) tables += 1;
                if (chkChipTags.Checked) tables += 2;

                this.gbTables.Enabled = false;

                this.progress.Maximum = tables;
                this.progress.Value = 0;

                this.lblProgress.Text = "Sťahujem číselníky ...";

                // Upload in background
                this.bResult = false;
                this.bCompetition = false;
                this.bTables = true;
                this.dtStart = DateTime.Now;
                this.bw.RunWorkerAsync();
            }
        }

        private void tsbCompetition_Click(object sender, EventArgs e)
        {
            if (this.dgvData.CurrentRow == null)
            {
                MessageBox.Show("Vyberte preteky, prosím.", "Download", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (this.bw.IsBusy)
            {
                MessageBox.Show("Prebieha download, čakajte prosím!", "Download", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                int tables = 0;
                if (this.chkCompetition.Checked) tables += 1;
                if (this.chkDisciplineList.Checked) tables += 1;
                if (this.chkExtTextsForDisciplineList.Checked) tables += 1;
                if (this.chkCheckPoints.Checked) tables += 1;
                if (this.chkPerformances.Checked) tables += 1;
                if (this.chkExtTextsForPerformance.Checked) tables += 1;
                if (this.chkChipData.Checked) tables += 1;

                this.gbTables.Enabled = false;

                this.progress.Maximum = tables;
                this.progress.Value = 0;

                this.lblProgress.Text = "Sťahujem preteky ...";

                // Upload in background
                this.bResult = false;
                this.bCompetition = true;
                this.bTables = false;
                this.dtStart = DateTime.Now;
                this.bw.RunWorkerAsync();
            }
        }

        #endregion

        #region BackgroundWorker

        void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            int nProgress = 0;

            try
            {
                if (this.bCompetition)
                {
                    int competitionIdOnWeb = Convert.ToInt32(((DataRowView)this.dgvData.CurrentRow.DataBoundItem)["ID"]);

                    #region 1 Competitions

                    if (chkCompetition.Checked)
                    {
                        syncParams = new SyncParameters();
                        syncParams.ActiveTable = AtletisService.Tables.CompetitionsById;
                        syncParams.ID = competitionIdOnWeb;
                        syncParams.IDSpecified = true;
                        syncParams.ActiveTableSpecified = true;

                        DownloadHelper.DownloadFromWcf(syncParams);

                        Globals.ActiveCompetition = CompetitionHelper.ConvertToEntity(DatabaseHelper.GetCompetitionsByWebId(competitionIdOnWeb).Rows[0]);

                        nProgress += 1;
                        this.bw.ReportProgress(nProgress);
                    }

                    #endregion

                    #region 2 DisciplineList

                    if (chkDisciplineList.Checked)
                    {
                        syncParams = new SyncParameters();
                        syncParams.ActiveTable = AtletisService.Tables.DisciplineListForCompetition;
                        syncParams.ActiveTableSpecified = true;
                        syncParams.ID = competitionIdOnWeb;
                        syncParams.IDSpecified = true;

                        DownloadHelper.DownloadFromWcf(syncParams);

                        nProgress += 1;
                        this.bw.ReportProgress(nProgress);
                    }

                    #endregion

                    #region 3 ExtTextsForDisciplineList

                    if (chkExtTextsForDisciplineList.Checked)
                    {
                        this.syncParams = new SyncParameters();
                        this.syncParams.ActiveTable = AtletisService.Tables.ExtTextsForDisciplineList;
                        this.syncParams.ActiveTableSpecified = true;

                        foreach (DataRow drDisciplineList in DatabaseHelper.GetDisciplineListByCompetitionIdActive(Globals.ActiveCompetition.ID)) // new DisciplineListTableAdapter().GetByCompetitionId(Globals.ActiveCompetition.ID))
                        {
                            this.syncParams.ID = Convert.ToInt32(drDisciplineList["WebId"]);
                            this.syncParams.IDSpecified = true;

                            DownloadHelper.DownloadFromWcf(syncParams);
                        }

                        nProgress += 1;
                        this.bw.ReportProgress(nProgress);
                    }

                    #endregion

                    #region 4 CheckPoints

                    if (chkCheckPoints.Checked)
                    {
                        this.syncParams = new SyncParameters();
                        this.syncParams.ActiveTable = AtletisService.Tables.CheckPoints;
                        this.syncParams.ActiveTableSpecified = true;

                        foreach (DataRow drDisciplineList in DatabaseHelper.GetDisciplineListByCompetitionIdActive(Globals.ActiveCompetition.ID))
                        {
                            this.syncParams.ID = Convert.ToInt32(drDisciplineList["WebId"]);
                            this.syncParams.IDSpecified = true;

                            DownloadHelper.DownloadFromWcf(syncParams);
                        }

                        nProgress += 1;
                        this.bw.ReportProgress(nProgress);
                    }

                    #endregion

                    #region 5 Performances

                    if (chkPerformances.Checked)
                    {
                        this.syncParams = new SyncParameters();
                        this.syncParams.ActiveTable = AtletisService.Tables.Performances;
                        this.syncParams.ActiveTableSpecified = true;
                        this.syncParams.ID = competitionIdOnWeb;
                        this.syncParams.IDSpecified = true;

                        DownloadHelper.DownloadFromWcf(syncParams);

                        nProgress += 1;
                        this.bw.ReportProgress(nProgress);
                    }

                    #endregion

                    #region 6 ExtTextsForPerformance

                    if (chkExtTextsForPerformance.Checked)
                    {
                        this.syncParams = new SyncParameters();
                        this.syncParams.ActiveTable = AtletisService.Tables.ExtTextsForPerformance;
                        this.syncParams.ActiveTableSpecified = true;

                        foreach (DataRow drDisciplineList in DatabaseHelper.GetDisciplineListByCompetitionIdActive(Globals.ActiveCompetition.ID)) // new DisciplineListTableAdapter().GetByCompetitionId(Globals.ActiveCompetition.ID))
                        {
                            foreach (DataRow drPerformance in DatabaseHelper.GetPerformancesByDisciplineListId(Convert.ToInt32(drDisciplineList["ID"]))) // new PerformancesTableAdapter().GetByDisciplineListId(Convert.ToInt32(drDisciplineList["ID"])))
                            {
                                this.syncParams.ID = Convert.ToInt32(drPerformance["WebId"]);
                                this.syncParams.IDSpecified = true;

                                DownloadHelper.DownloadFromWcf(syncParams);
                            }
                        }

                        nProgress += 1;
                        this.bw.ReportProgress(nProgress);
                    }

                    #endregion

                }

                if (this.bTables)
                {
                    #region 1 Categories

                    if (this.chkCategories.Checked)
                    {
                        syncParams = new SyncParameters();
                        syncParams.ActiveTable = AtletisService.Tables.Categories;
                        syncParams.ActiveTableSpecified = true;
                        DownloadHelper.DownloadFromWcf(syncParams);

                        nProgress += 1;
                        this.bw.ReportProgress(nProgress);
                    }

                    #endregion

                    #region 2,3 Disciplines

                    if (this.chkDisciplines.Checked)
                    {
                        syncParams = new SyncParameters();
                        syncParams.ActiveTable = AtletisService.Tables.DisciplinesGroups;
                        syncParams.ActiveTableSpecified = true;
                        DownloadHelper.DownloadFromWcf(syncParams);

                        nProgress += 1;
                        this.bw.ReportProgress(nProgress);

                        syncParams = new SyncParameters();
                        syncParams.ActiveTable = AtletisService.Tables.Disciplines;
                        syncParams.ActiveTableSpecified = true;
                        DownloadHelper.DownloadFromWcf(syncParams);

                        nProgress += 1;
                        this.bw.ReportProgress(nProgress);
                    }

                    #endregion

                    #region 4 Countries

                    if (this.chkCountries.Checked)
                    {
                        syncParams = new SyncParameters();
                        syncParams.ActiveTable = AtletisService.Tables.Countries;
                        syncParams.ActiveTableSpecified = true;
                        DownloadHelper.DownloadFromWcf(syncParams);

                        nProgress += 1;
                        this.bw.ReportProgress(nProgress);
                    }

                    #endregion

                    #region 5,6 Clubs

                    if (this.chkClubs.Checked)
                    {
                        syncParams = new SyncParameters();
                        syncParams.ActiveTable = AtletisService.Tables.ClubsGroups;
                        syncParams.ActiveTableSpecified = true;
                        DownloadHelper.DownloadFromWcf(syncParams);

                        nProgress += 1;
                        this.bw.ReportProgress(nProgress);

                        syncParams = new SyncParameters();
                        syncParams.ActiveTable = AtletisService.Tables.Clubs;
                        syncParams.ActiveTableSpecified = true;
                        DownloadHelper.DownloadFromWcf(syncParams);

                        nProgress += 1;
                        this.bw.ReportProgress(nProgress);
                    }

                    #endregion

                    #region 7 Competitors

                    if (this.chkCompetitors.Checked)
                    {
                        syncParams = new SyncParameters();
                        syncParams.ActiveTable = AtletisService.Tables.Competitors;
                        syncParams.ActiveTableSpecified = true;
                        DownloadHelper.DownloadFromWcf(syncParams);

                        nProgress += 1;
                        this.bw.ReportProgress(nProgress);
                    }

                    #endregion

                    #region 8,9 ChipTags

                    if (this.chkChipTags.Checked)
                    {
                        syncParams = new SyncParameters();
                        syncParams.ActiveTable = AtletisService.Tables.ChipTagsGroups;
                        syncParams.ActiveTableSpecified = true;
                        DownloadHelper.DownloadFromWcf(syncParams);

                        nProgress += 1;
                        this.bw.ReportProgress(nProgress);

                        syncParams = new SyncParameters();
                        syncParams.ActiveTable = AtletisService.Tables.ChipTags;
                        syncParams.ActiveTableSpecified = true;
                        DownloadHelper.DownloadFromWcf(syncParams);

                        nProgress += 1;
                        this.bw.ReportProgress(nProgress);
                    }

                    #endregion
                }

                this.bResult = true;
            }
            catch (FaultException ex)
            {
                MessageBox.Show(ex.Message, "Download", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Download", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.progress.Value = e.ProgressPercentage;
        }

        void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.gbTables.Enabled = true;
            TimeSpan tsDuration = DateTime.Now - this.dtStart;
            this.lblProgress.Text = string.Format("Upload dokončený, čas: {0:00}:{1:00}", tsDuration.Minutes, tsDuration.Seconds);

            if (bResult)
            {
                MessageBox.Show("Download úspešne ukončený!", "Download", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Pri downloade nastali chyby!", "Download", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        #endregion
        









    }
}
